package com.m3958.firstgwt.server.ftpserver;

import java.io.IOException;

import org.apache.ftpserver.ftplet.DataConnection;
import org.apache.ftpserver.ftplet.DefaultFtpReply;
import org.apache.ftpserver.ftplet.DefaultFtplet;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.ftplet.FtpSession;
import org.apache.ftpserver.ftplet.FtpletContext;
import org.apache.ftpserver.ftplet.FtpletResult;

public class MyFtplet extends DefaultFtplet{
	
	private FtpletContext ftpletContext;
	
	@Override
    public void init(FtpletContext ftpletContext) throws FtpException {
		this.ftpletContext = ftpletContext;
    }
	
	@Override
    public FtpletResult afterCommand(FtpSession session, FtpRequest request, FtpReply reply)
    	throws FtpException, IOException {

		// the reply is ignored for these callbacks
		
		String command = request.getCommand().toUpperCase();
		
		if ("PASS".equals(command)) {
		    return onLogin(session, request);
		} else if ("DELE".equals(command)) {
		    return onDeleteEnd(session, request);
		} else if ("STOR".equals(command)) {
		    return onUploadEnd(session, request,reply);
		} else if ("RETR".equals(command)) {
		    return onDownloadEnd(session, request);
		} else if ("RMD".equals(command)) {
		    return onRmdirEnd(session, request);
		} else if ("MKD".equals(command)) {
		    return onMkdirEnd(session, request);
		} else if ("APPE".equals(command)) {
		    return onAppendEnd(session, request);
		} else if ("STOU".equals(command)) {
		    return onUploadUniqueEnd(session, request);
		} else if ("RNTO".equals(command)) {
		    return onRenameEnd(session, request);
		} else {
		    // TODO should we call a catch all?
		    return null;
		}
    }
	
	@Override
    public FtpletResult onUploadStart(FtpSession session, FtpRequest request)
    	throws FtpException, IOException {
		printMsg(request.getCommand());
//		try {
//			DataConnection  out = session.getDataConnection().openConnection();
//			out.transferToClient(session, new DefaultFtpReply(FtpReply.REPLY_500_SYNTAX_ERROR_COMMAND_UNRECOGNIZED, "disk quota limit.").toString());
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//    	return FtpletResult.DISCONNECT;
		return null;
    }

	private FtpletResult onUploadEnd(FtpSession session, FtpRequest request,
			FtpReply reply) {
		return null;
	}
	
	private void printMsg(String msg){
		System.out.println(msg);
	}
	
	private void printMsg(int msg){
		System.out.println(msg);
	}
}
